package com.ziyia.a8_2_1;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class MainActivity extends AppCompatActivity {
    public static final String FILE_NAME = "test.txt";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void write(View view) throws IOException {
        FileOutputStream fileOutput = openFileOutput(FILE_NAME, MODE_APPEND);

        PrintStream ps = new PrintStream(fileOutput);
        ps.println("" + System.currentTimeMillis());
        ps.flush();

        ps.close();
        fileOutput.close();


        alert("write", "OK");

    }

    public void read(View view) throws IOException {
        FileInputStream fileInput = openFileInput(FILE_NAME);
        byte[] bytes = new byte[1024];
        int hasRead = 0;
        StringBuilder builder = new StringBuilder();
        while ((hasRead = fileInput.read(bytes)) != -1) {
            builder.append(new String(bytes, 0, hasRead));
        }

        alert("read", builder.toString());
    }

    private void alert(String title, String text) {
        new AlertDialog.Builder(this)
                .setTitle(title)
                .setMessage(text)
                .create()
                .show();
    }
}